#ifndef __SCATTERLIST_H__
#define __SCATTERLIST_H__
#include <cnix/string.h>
#include <cnix/page.h>
#include <cnix/mm.h>

extern unsigned long page_to_phys(struct page *page);

/* Define sg_next is an inline routine now in case we want to change
   scatterlist to a linked list later. */
static inline struct scatterlist *sg_next(struct scatterlist *sg)
{
  return sg + 1;
}

static inline struct page *sg_page(struct scatterlist *sg)
{
  return (struct page *)((sg)->page_link & ~0x3);
}

static inline unsigned long sg_phys(struct scatterlist *sg)
{
  return page_to_phys(sg_page(sg)) + sg->offset;
} 

static inline void sg_assign_page(struct scatterlist *sg, struct page *page)
{
  unsigned long page_link = sg->page_link & 0x3;

  /*
   * In order for the low bit stealing approach to work, pages
   * must be aligned at a 32-bit boundary as a minimum.
   */
  if(unlikely((unsigned long) page & 0x03)){
		printk("Bit stealing seems to be rejected.\n");
		while(1);
	}
  sg->page_link = page_link | (unsigned long) page;
}

static inline void sg_set_page(struct scatterlist *sg, struct page *page,
             unsigned int len, unsigned int offset)
{
  sg_assign_page(sg, page);
  sg->offset = offset;
  sg->length = len;
}

static inline void sg_set_buf(struct scatterlist *sg, const void *buf,
            unsigned int buflen)
{
  sg_set_page(sg, virt_to_page(buf), buflen, offset_in_page(buf));
}

static inline void sg_mark_end(struct scatterlist *sg)
{        
  /*
   * Set termination bit, clear potential chain bit
   */
  sg->page_link |= 0x02;
  sg->page_link &= ~0x01;
} 

static void sg_init_table(struct scatterlist *sgl, unsigned int nents)
{
  memset(sgl, 0, sizeof(*sgl) * nents);
  sg_mark_end(&sgl[nents - 1]);
}

/*
 * Loop over each sg element, following the pointer to a new list if necessary
 */
#define for_each_sg(sglist, sg, nr, __i)  \
  for (__i = 0, sg = (sglist); __i < (nr); __i++, sg = sg_next(sg))

#endif
